package com.googlecode.jascii.util;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ShellEngineFactory {
	private  ThreadLocal threadLocal = new ThreadLocal();
	private static ShellEngineFactory shellEngine = null ;
	
	private ShellEngineFactory(){}
	public static ShellEngineFactory getInstance()
	{
		if(shellEngine==null)
			shellEngine = new ShellEngineFactory();
		return shellEngine;
	}
	public void renewShellEngine(){
		
		threadLocal.remove();
	}
	
	
	public  Invocable getInvocable(StringBuffer shellScript)
	{
		Invocable invocable = (Invocable)threadLocal.get();
		if(invocable==null)
		{
			ScriptEngineManager manager = new ScriptEngineManager();
	        ScriptEngine engine = manager.getEngineByExtension("js");
	        try {
				engine.eval(shellScript.toString());
				 //
	            // Convert / cast the engine into invocable engine.
	            //
				invocable = (Invocable) engine;
				threadLocal.set(invocable);
			} catch (ScriptException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return invocable;
		
		
	}


	
}
